interface CandidateData {
  _id?: string;
  name: string;
  description: string;
  images: string[];
  videoUrl: string;
  videoPoster?: string;
  audioUrl: string;
  extraInfo: string;
  activityId?: string;
}

Page({
  data: {
    isEdit: false,
    activityId: '',
    candidate: {
      _id: '',
      name: '',
      description: '',
      images: [] as string[],
      videoUrl: '',
      videoPoster: '',
      audioUrl: '',
      extraInfo: ''
    } as CandidateData,
    loading: false,
    loadingText: '加载中...'
  },

  onLoad(options: any) {
    // 获取活动ID
    const activityId = options.activityId || ''
    
    // 判断是创建还是编辑
    if (options.id) {
      this.setData({
        isEdit: true,
        activityId: activityId,
        'candidate._id': options.id
      })
      
      // 获取候选人详情
      this.getCandidateDetail(options.id)
    } else {
      this.setData({
        activityId: activityId
      })
    }
  },

  // 获取候选人详情
  async getCandidateDetail(candidateId: string) {
    this.setData({
      loading: true,
      loadingText: '加载中...'
    })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'candidateManager',
        data: {
          action: 'getDetail',
          candidateId: candidateId
        }
      })

      const response = result.result as any
      if (response && response.success) {
        this.setData({
          candidate: response.data
        })
        
        console.log('获取候选人详情成功:', response.data)
      } else {
        wx.showToast({
          title: response?.message || '获取候选人详情失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('获取候选人详情失败:', error)
      wx.showToast({
        title: '获取候选人详情失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.setData({
        loading: false
      })
    }
  },

  // 输入候选人姓名
  inputName(e: any) {
    this.setData({
      'candidate.name': e.detail.value
    })
  },

  // 输入候选人描述
  inputDescription(e: any) {
    this.setData({
      'candidate.description': e.detail.value
    })
  },

  // 输入额外信息
  inputExtraInfo(e: any) {
    this.setData({
      'candidate.extraInfo': e.detail.value
    })
  },

  // 选择图片
  chooseImage() {
    const { candidate } = this.data
    const remainingCount = 12 - candidate.images.length // 改为最多12张图片
    
    if (remainingCount <= 0) {
      wx.showToast({
        title: '最多只能上传12张图片',
        icon: 'none'
      })
      return
    }

    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 检查图片文件格式
        const supportedFormats = ['jpg', 'jpeg', 'png', 'pdf']
        const validFiles = res.tempFilePaths.filter(filePath => {
          const fileExtension = filePath.split('.').pop()?.toLowerCase()
          return supportedFormats.includes(fileExtension || '')
        })

        if (validFiles.length !== res.tempFilePaths.length) {
          wx.showToast({
            title: '仅支持JPG、PNG、PDF格式',
            icon: 'none'
          })
        }

        if (validFiles.length > 0) {
          // 批量上传图片
          this.uploadImages(validFiles)
        }
      }
    })
  },

  // 批量上传图片到云存储
  async uploadImages(tempFilePaths: string[]) {
    this.setData({
      loading: true,
      loadingText: '上传图片中...'
    })
    
    try {
      const { candidate } = this.data
      const candidateId = candidate._id || Date.now().toString() // 使用临时ID
      
      const uploadPromises = tempFilePaths.map(async (tempFilePath, index) => {
        // 获取文件扩展名
        const fileExtension = tempFilePath.split('.').pop()?.toLowerCase() || 'jpg'
        
        // 生成文件名：candidates/galleries/候选人ID_图片索引.扩展名
        const imageIndex = candidate.images.length + index
        const fileName = `candidates/galleries/${candidateId}_${imageIndex}.${fileExtension}`
        
        // 上传到云存储
        const uploadResult = await wx.cloud.uploadFile({
          cloudPath: fileName,
          filePath: tempFilePath
        })
        
        return uploadResult.fileID
      })
      
      const uploadedFileIDs = await Promise.all(uploadPromises)
      
      // 更新图片列表
      const newImages = [...this.data.candidate.images, ...uploadedFileIDs]
      this.setData({
        'candidate.images': newImages
      })
      
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })
      
      console.log('图片上传成功:', uploadedFileIDs)
    } catch (error) {
      console.error('上传图片失败:', error)
      wx.showToast({
        title: '上传失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.setData({
        loading: false
      })
    }
  },

  // 预览图片
  previewImage(e: any) {
    const index = e.currentTarget.dataset.index
    const { candidate } = this.data
    
    wx.previewImage({
      current: candidate.images[index],
      urls: candidate.images
    })
  },

  // 删除图片
  deleteImage(e: any) {
    const index = e.currentTarget.dataset.index
    const images = [...this.data.candidate.images]
    images.splice(index, 1)
    
    this.setData({
      'candidate.images': images
    })
  },

  // 选择视频
  chooseVideo() {
    console.log('选择视频功能被调用')
    
    const that = this
    
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      maxDuration: 300, // 最长5分钟
      camera: 'back',
      success: (res) => {
        console.log('选择视频成功:', res)
        const tempFilePath = res.tempFiles[0].tempFilePath
        const fileSize = res.tempFiles[0].size
        
        // 检查文件大小（限制50MB）
        const maxSize = 50 * 1024 * 1024
        if (fileSize > maxSize) {
          wx.showToast({
            title: '视频文件过大，请选择小于50MB的视频',
            icon: 'none',
            duration: 3000
          })
          return
        }
        
        // 设置临时视频路径以供预览
        this.setData({
          'candidate.videoUrl': tempFilePath
        })
        
        // 立即上传视频
        this.uploadVideo(tempFilePath)
      },
      fail: (err) => {
        console.error('选择视频失败:', err)
        
        // 如果wx.chooseMedia失败，回退到wx.chooseVideo
        wx.chooseVideo({
          sourceType: ['album', 'camera'],
          maxDuration: 300,
          success: (res) => {
            console.log('选择视频成功(回退方式):', res)
            
            // 检查文件大小
            const maxSize = 50 * 1024 * 1024
            if (res.size > maxSize) {
              wx.showToast({
                title: '视频文件过大，请选择小于50MB的视频',
                icon: 'none',
                duration: 3000
              })
              return
            }
            
            // 设置临时视频路径
            this.setData({
              'candidate.videoUrl': res.tempFilePath
            })
            
            // 上传视频
            this.uploadVideo(res.tempFilePath)
          },
          fail: (err2) => {
            console.error('选择视频完全失败:', err2)
            wx.showModal({
              title: '选择视频失败',
              content: '无法选择视频文件，请检查权限设置',
              showCancel: false
            })
          }
        })
      }
    })
  },

  // 上传视频到云存储
  async uploadVideo(tempFilePath: string) {
    this.setData({
      loading: true,
      loadingText: '上传视频中...'
    })
    
    try {
      const { candidate } = this.data
      // 生成唯一的文件ID，如果没有候选人ID则生成临时ID
      const candidateId = candidate._id || 'temp_' + Date.now()
      
      // 获取文件扩展名
      const fileName = tempFilePath.split('/').pop() || 'video.mp4'
      const fileExtension = fileName.split('.').pop()?.toLowerCase() || 'mp4'
      
      // 生成云存储路径：candidates/videos/候选人ID_时间戳.扩展名
      const timestamp = Date.now()
      const cloudPath = `candidates/videos/${candidateId}_${timestamp}.${fileExtension}`
      
      console.log('开始上传视频:', cloudPath)
      
      // 上传到云存储
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: tempFilePath
      })
      
      console.log('视频上传结果:', uploadResult)
      
      if (uploadResult.fileID) {
        // 更新视频URL为云存储文件ID
        this.setData({
          'candidate.videoUrl': uploadResult.fileID
        })
        
        wx.showToast({
          title: '视频上传成功',
          icon: 'success'
        })
        
        console.log('视频上传成功，文件ID:', uploadResult.fileID)
      } else {
        throw new Error('上传结果中没有文件ID')
      }
    } catch (error: any) {
      console.error('上传视频失败:', error)
      
      // 上传失败时恢复原始状态
      this.setData({
        'candidate.videoUrl': ''
      })
      
      wx.showModal({
        title: '上传失败',
        content: '视频上传失败：' + (error.message || '未知错误'),
        showCancel: false
      })
    } finally {
      this.setData({
        loading: false
      })
    }
  },

  // 删除视频
  deleteVideo() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个视频吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            'candidate.videoUrl': '',
            'candidate.videoPoster': ''
          })
        }
      }
    })
  },

  // 选择音频文件
  chooseAudio() {
    console.log('选择音频功能被调用')
    
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        console.log('选择文件成功:', res)
        const tempFile = res.tempFiles[0]
        const filePath = tempFile.path
        const fileSize = tempFile.size
        const fileName = tempFile.name
        
        // 检查文件扩展名
        const supportedFormats = ['mp3', 'wav', 'aac', 'm4a', 'ogg', 'flac', 'wma', 'mp4']
        const fileExtension = fileName.split('.').pop()?.toLowerCase()
        
        if (!fileExtension || !supportedFormats.includes(fileExtension)) {
          wx.showToast({
            title: '仅支持音频格式：MP3、WAV、AAC、M4A、OGG、FLAC、WMA、MP4',
            icon: 'none',
            duration: 3000
          })
          return
        }
        
        // 检查文件大小（限制20MB）
        const maxSize = 20 * 1024 * 1024
        if (fileSize > maxSize) {
          wx.showToast({
            title: '音频文件过大，请选择小于20MB的音频',
            icon: 'none',
            duration: 3000
          })
          return
        }
        
        // 上传音频
        this.uploadAudio(filePath, fileExtension)
      },
      fail: (err) => {
        console.error('选择音频失败:', err)
        wx.showModal({
          title: '选择音频失败',
          content: '无法选择音频文件，请检查权限设置',
          showCancel: false
        })
      }
    })
  },

  // 上传音频到云存储
  async uploadAudio(tempFilePath: string, fileExtension: string) {
    this.setData({
      loading: true,
      loadingText: '上传音频中...'
    })
    
    try {
      const { candidate } = this.data
      // 生成唯一的文件ID，如果没有候选人ID则生成临时ID
      const candidateId = candidate._id || 'temp_' + Date.now()
      
      // 生成云存储路径：candidates/audios/候选人ID_时间戳.扩展名
      const timestamp = Date.now()
      const cloudPath = `candidates/audios/${candidateId}_${timestamp}.${fileExtension}`
      
      console.log('开始上传音频:', cloudPath)
      
      // 上传到云存储
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: tempFilePath
      })
      
      console.log('音频上传结果:', uploadResult)
      
      if (uploadResult.fileID) {
        // 更新音频URL为云存储文件ID
        this.setData({
          'candidate.audioUrl': uploadResult.fileID
        })
        
        wx.showToast({
          title: '音频上传成功',
          icon: 'success'
        })
        
        console.log('音频上传成功，文件ID:', uploadResult.fileID)
      } else {
        throw new Error('上传结果中没有文件ID')
      }
    } catch (error: any) {
      console.error('上传音频失败:', error)
      
      // 上传失败时恢复原始状态
      this.setData({
        'candidate.audioUrl': ''
      })
      
      wx.showModal({
        title: '上传失败',
        content: '音频上传失败：' + (error.message || '未知错误'),
        showCancel: false
      })
    } finally {
      this.setData({
        loading: false
      })
    }
  },

  // 删除音频
  deleteAudio() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个音频吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            'candidate.audioUrl': ''
          })
        }
      }
    })
  },

  // 保存候选人
  async saveCandidate() {
    const { candidate, isEdit, activityId } = this.data
    
    // 验证必填项
    if (!candidate.name.trim()) {
      wx.showToast({
        title: '请输入候选人姓名',
        icon: 'none'
      })
      return
    }
    
    // 如果没有活动ID，说明是在活动创建过程中添加候选人
    // 直接返回数据给上一页，不保存到数据库
    if (!activityId) {
      const candidateData = {
        _id: Date.now().toString(), // 临时ID
        name: candidate.name.trim(),
        description: candidate.description.trim(),
        images: candidate.images,
        videoUrl: candidate.videoUrl,
        videoPoster: candidate.videoPoster || '',
        audioUrl: candidate.audioUrl || '',
        extraInfo: candidate.extraInfo.trim(),
        isTemp: true // 标记为临时数据
      }
      
      // 返回上一页并传递候选人数据
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      
      if (prevPage && prevPage.addCandidateCallback) {
        prevPage.addCandidateCallback(candidateData)
      }
      
      wx.navigateBack()
      return
    }
    
    this.setData({
      loading: true,
      loadingText: isEdit ? '保存中...' : '创建中...'
    })
    
    try {
      // 构建候选人数据
      const candidateData: any = {
        name: candidate.name.trim(),
        description: candidate.description.trim(),
        images: candidate.images,
        videoUrl: candidate.videoUrl,
        videoPoster: candidate.videoPoster || '',
        audioUrl: candidate.audioUrl || '',
        extraInfo: candidate.extraInfo.trim(),
        activityId: activityId
      }
      
      let result
      
      if (isEdit) {
        // 更新候选人
        result = await wx.cloud.callFunction({
          name: 'candidateManager',
          data: {
            action: 'update',
            candidateId: candidate._id,
            candidateData: candidateData
          }
        })
      } else {
        // 创建候选人
        result = await wx.cloud.callFunction({
          name: 'candidateManager',
          data: {
            action: 'create',
            candidateData: candidateData
          }
        })
      }

      const response = result.result as any
      if (response && response.success) {
        wx.showToast({
          title: isEdit ? '保存成功' : '创建成功',
          icon: 'success',
          success: () => {
            setTimeout(() => {
              // 只有在创建新候选人时才调用回调函数
              if (!isEdit) {
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                
                if (prevPage && prevPage.addCandidateCallback) {
                  prevPage.addCandidateCallback(response.data)
                }
              }
              
              wx.navigateBack()
            }, 1500)
          }
        })
        
        console.log('候选人保存成功:', response.data)
      } else {
        wx.showToast({
          title: response?.message || '操作失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('保存候选人失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.setData({
        loading: false
      })
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 测试视频选择功能
  testVideoSelection() {
    console.log('测试视频选择功能')
    
    // 测试基础的chooseVideo API
    try {
      if (typeof wx.chooseVideo === 'function') {
        console.log('wx.chooseVideo API 可用')
        wx.chooseVideo({
          sourceType: ['album'],
          success: (res) => {
            console.log('选择视频成功:', res)
            wx.showToast({
              title: '测试成功',
              icon: 'success'
            })
          },
          fail: (err) => {
            console.error('选择视频失败:', err)
            wx.showToast({
              title: '测试失败: ' + err.errMsg,
              icon: 'none',
              duration: 3000
            })
          }
        })
      } else {
        console.log('wx.chooseVideo API 不可用')
        wx.showToast({
          title: 'chooseVideo API 不可用',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('测试出错:', error)
      wx.showToast({
        title: '测试出错',
        icon: 'none'
      })
    }
  },
}) 